<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { statisticsIndustry, statisticsArea } from '@/api/charts'
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    color: {
      type: String,
      default: '#41c7c9'
    },
    order: {
      type: String,
      default: ''
    }, // 接口orderBy
    yaxis: {
      type: String,
      default: ''
    }, // y轴显示的字段
    isRate: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    }// 地区还是行业
  },
  data() {
    return {
      chart: null,
      parms: {
        orderBy: this.order,
        pageNo: 1,
        pageSize: 10
      }
    }
  },
  mounted() {
    if (this.type === 'industry') {
      statisticsIndustry(this.parms).then(response => {
        const x = []; const y = []
        response.result.records.forEach((item) => {
          x.push(item.name)
          y.push(this.isRate ? item[this.yaxis] : item[this.yaxis])
        })
        this.initChart(x, y)
      })
    } else if (this.type === 'area') {
      statisticsArea(this.parms).then(response => {
        const x = []; const y = []
        response.result.records.forEach((item) => {
          x.push(item.name)
          y.push(this.isRate ? item[this.yaxis] : item[this.yaxis])
        })
        this.initChart(x, y)
      })
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(xaxisData, yaxisData) {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        color: [this.color],
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: !this.isRate ? 30 : 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: xaxisData,
          axisLabel: {
            interval: 0,
            rotate: 40
          }
        }],
        yAxis: [{
          minInterval: 1,
          type: 'value',
          axisLabel: {
            formatter: this.isRate ? '{value}%' : '{value}'
          },
          name: !this.isRate ? '单位/个' : ''
        }],
        series: [{
          data: yaxisData,
          type: 'bar',
          barWidth: '50%',
          barCategoryGap: 50
        }]
      })
    }
  }
}
</script>
